package com.devicemantra.coordinate.interfaces.call;

import java.io.IOException;

import javax.jdo.JDOObjectNotFoundException;
import com.devicemantra.coordinate.dataobjects.*;
import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.devicemantra.coordinate.interfaces.email.CSendEmail;
import com.devicemantra.coordinate.ds.tests.PMF;
import com.devicemantra.coordinate.util.CLogger;
import com.twilio.sdk.verbs.Gather;
import com.twilio.sdk.verbs.Say;
import com.twilio.sdk.verbs.TwiMLException;
import com.twilio.sdk.verbs.TwiMLResponse;

public class AuthMobileUser extends HttpServlet 
{
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws IOException 
	{
		doGet(req,resp);
	}
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
	
		String lMessageId = req.getParameter("id");
		System.out.println("Id we got was " + lMessageId);
		
		boolean lDoesExist = true;
		String lAuthMesgId = lMessageId;
		PersistenceManager lPMF = PMF.get().getPersistenceManager();
		CAuthMobileMessage lAuthMessageObj = null;
		try
		{
			lAuthMessageObj = lPMF.getObjectById(CAuthMobileMessage.class,lAuthMesgId);
		} catch(JDOObjectNotFoundException e)
		{
			lDoesExist = false;
		}
		
		if(false == lDoesExist)
		{
			System.out.println("FATAL ERROR: The message id does not exist :" + lAuthMesgId);
			return;
		}
		System.out.println("The message retreived is " + lAuthMessageObj);
		System.out.println("Serving message to Twilio");
		TwiMLResponse lResponse = new TwiMLResponse();
		Gather lGather = new Gather();
		lGather.setAction("/operations/authenticate/call/CollectDigitsCall?id=" + lAuthMessageObj.getMessageId());
		lGather.setMethod("POST");
		lGather.setNumDigits(4);
		
		Say lSay = new Say("Good afternoon " + lAuthMessageObj.getAuthUserName() + ", Please enter your 4 digit authentication code sent to your email address, at  "  + lAuthMessageObj.getAuthEmailId() );
		lSay.setVoice("woman");
		
		
		try {
			lResponse.append(lSay);
			lResponse.append(lGather);
			
		} catch (TwiMLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		resp.setContentType("text/xml");
		resp.getOutputStream().print(lResponse.toXML());
		System.out.println("Sending Response : " + lResponse.toXML());
		
		
	}
}
